package com.lst.servlet;


import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.common.JPushEnum;
import com.lst.common.JPushMessage;
import com.lst.entity.request.JiluLogReqPara;
import com.lst.model.Answer;
import com.lst.model.Dynamic;
import com.lst.model.JiluLog;
import com.lst.model.MstClient;
import com.lst.model.MstMessage;
import com.lst.service.AnswerService;
import com.lst.service.DynamicService;
import com.lst.service.JiluLogService;
import com.lst.service.MstClientService;
import com.lst.service.MstMessageService;
import com.lst.utils.RequestUtils;


/**
 * @ClassName: JiluLogAddServlet
 * @Description: 喜欢添加、取消接口
 * 
 */
public class JiluLogAddServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private JiluLogService jiluLogService = ctx.getBean(JiluLogService.class);
	
	private MstClientService mstClientService = ctx.getBean(MstClientService.class);
	
	private MstMessageService mstMessageService = ctx.getBean(MstMessageService.class);
	
	private DynamicService dynamicService = ctx.getBean(DynamicService.class);
	
	private AnswerService answerService = ctx.getBean(AnswerService.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		BaseResponse resPara = new BaseResponse();

		try {
			JiluLogReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
			int userid = Integer.parseInt(reqPara.getUserid());
			int jiluType = Integer.parseInt(reqPara.getJiluType());	
			int sourceId = Integer.parseInt(reqPara.getSourceId());
			
			int friendId=0;
			if(jiluType==1){
				Dynamic dynamic=dynamicService.selectByPrimaryKey(sourceId);
				if(dynamic!=null){
					friendId=dynamic.getCreateuser();
				}
			}else{
				Answer answer=answerService.selectByPrimaryKey(sourceId);
				if(answer!=null){
					friendId=answer.getAnswerCreateUser();
				}
			}
		
			
			Map<String, Object> reqMap = new HashMap<String, Object>();

			reqMap.put("createUser", userid);
			reqMap.put("jiluType", jiluType);
			reqMap.put("sourceId", sourceId);		
			JiluLog jilu=jiluLogService.queryByMap(reqMap);
			if(jilu!=null){
				if(jilu.getIsLove()==true){
					jiluLogService.updateByKey(reqMap);
					resPara.setCode(CommCode.M_Y000000);
					resPara.setMessage("喜欢已取消");
				}else{
					jiluLogService.updateByMap(reqMap);
					resPara.setCode(CommCode.M_Y000000);
					resPara.setMessage("喜欢已添加");
					//关注发通知
					if(userid!=friendId){
							MstClient mstClient = mstClientService.selectByPrimaryKey(Integer.valueOf(userid));
							if (mstClient != null) {
								String name = mstClient.getNickname();

								MstMessage message = new MstMessage();
								message.setReceiveid(friendId);
								message.setReceivetype(CommCode.SYSCODE_MSG_TYPE_RECEIVE_CLIENT);
								message.setSendid(Integer.valueOf(userid));
								message.setSendtype(CommCode.SYSCODE_MSG_TYPE_SEND_CLIENT);
								message.setEnabled(true);
								message.setIsdeleted(false);
								message.setCreateuser(-1);
								message.setCreatedate(startDate);
								message.setReserved1(sourceId);
								if(jiluType==1){
								    message.setContent("喜欢了你的动态！");
								    message.setReserved2(CommCode.SYSTEM_CARESEL_RANGE_DYNAMIC);
								}else{
									message.setContent("喜欢了你的回答！");
								    message.setReserved2(CommCode.SYSTEM_CARESEL_RANGE_ANSWER);
								}
								message.setReserved7(false);
								message.setType(CommCode.SYSCODE_MSG_TYPE_PUSH);
								mstMessageService.insert(message);
								 message.setReserved12(name);
								JPushMessage.pushMessage(message, JPushEnum.ALL_ALIAS);
							}
					}
					
				   }	
			}else{
				JiluLog md = new JiluLog();
				md.setCreateUser(userid);
			    md.setJiluType(jiluType);
			    md.setSourceId(sourceId);
				md.setCreateDate(startDate);
				md.setIsDelete(false);
				md.setIsLove(true);
				jiluLogService.insert(md);
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage("喜欢已添加");
				
				//关注发通知
				if(userid!=friendId){
						MstClient mstClient = mstClientService.selectByPrimaryKey(Integer.valueOf(userid));
						if (mstClient != null) {
							String name = mstClient.getNickname();

							MstMessage message = new MstMessage();
							message.setReceiveid(friendId);
							message.setReceivetype(CommCode.SYSCODE_MSG_TYPE_RECEIVE_CLIENT);
							message.setSendid(Integer.valueOf(userid));
							message.setSendtype(CommCode.SYSCODE_MSG_TYPE_SEND_CLIENT);
							message.setEnabled(true);
							message.setIsdeleted(false);
							message.setCreateuser(-1);
							message.setCreatedate(startDate);
							message.setReserved1(sourceId);
							if(jiluType==1){
							    message.setContent("喜欢了你的动态！");
							    message.setReserved2(CommCode.SYSTEM_CARESEL_RANGE_DYNAMIC);
							}else{
								message.setContent("喜欢了你的回答！");
							    message.setReserved2(CommCode.SYSTEM_CARESEL_RANGE_ANSWER);
							}
							message.setReserved7(false);
							message.setType(CommCode.SYSCODE_MSG_TYPE_PUSH);
							mstMessageService.insert(message);
							 message.setReserved12(name);
							JPushMessage.pushMessage(message, JPushEnum.ALL_ALIAS);
						}
				}
				
			}
			
	
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
//			logger.info("ClientDiscussServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

//			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public JiluLogReqPara getReqPara(HttpServletRequest request) {

		JiluLogReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new JiluLogReqPara());

			reqPara = (JiluLogReqPara) baseRequest.clone();
			
			String userid = request.getParameter("userid");
			String jiluType = request.getParameter("jiluType");
			String sourceId = request.getParameter("sourceId");

//			logger.info("reqPara userid: " + userid);
//			logger.info("reqPara jiluType: " + jiluType);
//			logger.info("reqPara sourceId: " + sourceId);

	        reqPara.setUserid(userid);
			reqPara.setJiluType(jiluType);
	        reqPara.setSourceId(sourceId);
      
		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		JiluLogReqPara cdReqPara = (JiluLogReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

		if (StringUtils.isEmpty(cdReqPara.getJiluType())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("记录类型为空");
		}else if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		}else if (StringUtils.isEmpty(cdReqPara.getSourceId())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("记录目标id为空");
		}else {
			flag = true;
		}

		return  flag;
	}
	
	

}
